<?php

namespace turbo;

use think\Cache;

class Miniapp{

    const CACHE_HASH = 'MINIAPP_SERVER_ACCESSTOKEN';

    /**
     * 获取小程序码
     * 
     */
    public static function getMiniAppQrcode($scene, $page = 'pages/index/index'){
        // ACCESS_TOKEN
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.self::getAccessToken();

        $res = fhcurl($url, json_encode([
            'scene' => $scene,
            'page' => $page,
        ]));

        $re = json_decode($res, true);
            
        if($re && isset($re['errcode']) ){
            throw new \Exception(isset($re['errmsg']) ? $re['errmsg'] : '微信错误');
        }

        if(!$res){
            throw new \Exception('微信错误');
        }
        return $res;
    }

    /**
     * 获取小程序的AccessToken
     */
    public static function getAccessToken(){
        $cache = Cache::get(self::CACHE_HASH);

        if(!$cache){
            $conf = config('wxapp');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$conf['wxappid']}&secret={$conf['wxappsecret']}";
            $res = fhcurl($url);
            if($res){
                $res = json_decode($res, true);
            }
            if(!$res || !isset($res['access_token'])){
                throw new \Exception("Cannot get Wechat AccressToken");
            }

            $exp = isset($res['expires_in']) ? intval($res['expires_in']) - 60 : 3600;
            $cache = $res['access_token'];
            Cache::set(self::CACHE_HASH, $cache, $exp);
        }

        return $cache;
    }

}